﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Dynamic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace ARchGL.Platform.Utils
{
    /// <summary>
    /// 工具类库
    /// </summary>
    public class CommonHelper
    {
        public static string GetLocalIP()
        {
            try
            {
                var hostName = Dns.GetHostName(); //得到主机名
                var ipEntry = Dns.GetHostEntry(hostName);
                return ipEntry.AddressList[2].ToString();
            }
            catch 
            {
                return "";
            }
        }

        public static List<string> GetLocalIPList()
        {
            List<string> ipArr = new List<string>();
            try
            {
                var hostName = Dns.GetHostName(); //得到主机名
                var ipEntry = Dns.GetHostEntry(hostName);
                foreach (var ip in ipEntry.AddressList)
                {
                    if (!string.IsNullOrWhiteSpace(ip.ToString()))
                        ipArr.Add(ip.ToString());
                }
                return ipArr;
            }
            catch 
            {
                return ipArr;
            }
        }

        public static string GetIP()
        {
            string hostName = Dns.GetHostName(); //本机名
                                                //System.Net.IPAddress[] addressList = Dns.GetHostByName(hostName).AddressList;//会警告GetHostByName()已过期，我运行时且只返回了一个IPv4的地址
            System.Net.IPAddress[] addressList = Dns.GetHostAddresses(hostName); //会返回所有地址，包括IPv4和IPv6
            if (addressList.Length > 0)
            {
                return addressList[0].ToString();
            }
            return "";
        }

        /// <summary>
        /// 读取枚举 可扩展过滤
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static IEnumerable<ExpandoObject> ReadEnum(Type type)
        {
            foreach (var item in type.GetFields())
            {
                var description = item.GetCustomAttributes(typeof(DescriptionAttribute), true);
                var filter = item.GetCustomAttributes(typeof(FilterEnumIgnoreAttribute), true);
                if (item.FieldType.IsEnum && filter.SingleOrDefault() == null)
                {
                    dynamic d = new ExpandoObject();
                    d.Key = item.Name;
                    d.Value = item.GetRawConstantValue();
                    d.Description = description.SingleOrDefault() == null ? "" : ((DescriptionAttribute)description[0]).Description;
                    yield return d;
                }
            }
        }
    }
}
